/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ejb;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import jpa.Competenza;

@Stateless
public class GestioneCompetenze implements GestioneCompetenzeLocal{

    @PersistenceContext
    private EntityManager em;

    public List<Competenza> listaCompetenze() {
        Query query = em.createNamedQuery("Competenza.findAll");
        return query.getResultList();
    }

    public boolean aggiungi(Competenza competenza) {
        if(!controllaMateria(competenza)){
            em.persist(competenza);
            em.flush();
            return true;
        }
        return false;
    }

    public boolean rimuovi(Integer id) {
        Competenza c = em.find(Competenza.class, id);
        if(c!=null){
            em.remove(c);
            em.flush();
            return true;
        }
        return false;
    }

    private boolean controllaMateria(Competenza cu) {
        Query query = em.createNamedQuery("Competenza.findAll");
        List<Competenza> lista = query.getResultList();
        for(Competenza c :lista){
            if(c.getMateria().toUpperCase().equals(cu.getMateria().toUpperCase())) {
                return true;
            }
        }
        return false;
    }

    public String getCompetenza(Integer id) {
        Competenza s = em.find(Competenza.class, id);
        if (s==null) {
            return "";
        }
        return s.getMateria();
    }
}
